import React from 'react';
import { Form, Table, Radio, Select } from 'antd';
import { InfoIcon } from '@/molecules';
import LimitInput from '@/components/LimitInput';
import ProjectPreview from '../ProjectPreview';
import styles from './index.less';

const { Option } = Select;

const EVALUATION_LEVEL = ['', '优秀', '良好', '合格', '需观察', '不合格'];

const levelList = [
    { label: '5', value: 5 },
    { label: '4', value: 4 },
    { label: '3', value: 3 },
    { label: '2', value: 2 },
    { label: '1', value: 1 },
    { label: '0', value: 0 }
];

export default React.forwardRef(({ form, data }, ref) => {
    const { getFieldDecorator } = form;
    const [visible, setVisible] = React.useState(false);
    const [fullError, setFullError] = React.useState('');
    let { levels } = data || {};
    const assessTable = data;

    if (!levels || levels.length === 0) {
        levels = [
            {
                type: 1,
                min: 4,
                max: 5,
                qualified: 0,
                entry: 1
            },
            {
                type: 2,
                min: undefined,
                max: undefined,
                qualified: 0,
                entry: 0
            },
            {
                type: 3,
                min: 3,
                max: 4,
                qualified: 1,
                entry: 0
            },
            {
                type: 4,
                min: 2,
                max: 3,
                qualified: 0,
                entry: 0
            },
            {
                type: 5,
                min: 0,
                max: 2,
                qualified: 0,
                entry: 0
            }
        ];
    }

    const handleQualifiedChange = (e, type) => {
        if (e.target.value === 1) {
            const arr = [1, 2, 3, 4, 5].filter(it => it !== type);
            const obj = {};
            arr.forEach(it => {
                obj[`qualified${it}`] = 0;
            });
            form.setFieldsValue(obj);
            setTimeout(() => {
                form.validateFields(['entry1', 'entry2', 'entry3', 'entry4', 'entry5'], {
                    force: true,
                    scroll: { alignWithTop: true }
                });
            }, 10);
        }
    };

    const handleEntryChange = (e, type) => {
        if (e.target.value === 1) {
            const arr = [1, 2, 3, 4, 5].filter(it => it !== type);
            const obj = {};
            arr.forEach(it => {
                obj[`entry${it}`] = 0;
            });
            form.setFieldsValue(obj);
            setTimeout(() => {
                form.validateFields(['qualified1', 'qualified2', 'qualified3', 'qualified4', 'qualified5'], {
                    force: true,
                    scroll: { alignWithTop: true }
                });
            }, 10);
        }
    };

    const isError = (type, flag = 'min') => {
        const min = form.getFieldValue(`evaluationMin${type}`);
        const max = form.getFieldValue(`evaluationMax${type}`);
        if (flag === 'min') {
            return typeof max !== 'undefined' && typeof min === 'undefined' ? 'error' : '';
        }
        if (flag === 'max') {
            return typeof min !== 'undefined' && typeof max === 'undefined' ? 'error' : '';
        }
        return '';
    };

    const isError1 = type =>
        form.getFieldValue(`evaluationMin${type}`) >= form.getFieldValue(`evaluationMax${type}`) ? 'error' : '';

    const isError2 = type =>
        form.getFieldValue(`evaluationMax${type + 1}`) > form.getFieldValue(`evaluationMin${type}`) ? 'error' : '';

    React.useImperativeHandle(ref, () => ({
        check() {
            if (
                isError(1, 'min') ||
                isError(2, 'min') ||
                isError(3, 'min') ||
                isError(4, 'min') ||
                isError(5, 'min') ||
                isError(1, 'max') ||
                isError(2, 'max') ||
                isError(3, 'max') ||
                isError(4, 'max') ||
                isError(5, 'max') ||
                isError1(1) ||
                isError1(2) ||
                isError1(3) ||
                isError1(4) ||
                isError1(5) ||
                isError2(1) ||
                isError2(2) ||
                isError2(3) ||
                isError2(4)
            ) {
                setFullError('');
                return true;
            }
            const values = form.getFieldsValue();
            const evaluationDetail = [1, 2, 3, 4, 5]
                .map(item => ({
                    min: values?.[`evaluationMin${item}`],
                    max: values?.[`evaluationMax${item}`],
                    entry: values?.[`entry${item}`],
                    qualified: values?.[`qualified${item}`]
                }))
                .filter(item => typeof item.min !== 'undefined' && typeof item.max !== 'undefined');
            if (evaluationDetail?.length < 3) {
                setFullError('请保证至少填写三个等级；');
                return false;
            }
            let entry = 0;
            let qualified = 0;
            evaluationDetail.forEach(item => {
                if (item.entry > 0) {
                    entry = 1;
                }
                if (item.qualified > 0) {
                    qualified = 1;
                }
            });
            if (!qualified) {
                setFullError('请选择合格标准线；');
                return false;
            }
            if (!entry) {
                setFullError('请选择提前转正标准线；');
                return false;
            }
            const arr = [];
            evaluationDetail.forEach(item => {
                const { min, max } = item;
                for (let index = min + 1; index <= max; index += 1) {
                    arr.push(index);
                }
            });
            if ([...new Set(arr)].length < 5) {
                setFullError('请保证评分区间(0-5)完整；');
                return false;
            }
            setFullError('');
            return true;
        }
    }));

    const columns = [
        {
            title: '等级',
            dataIndex: 'level'
        },
        {
            title: '最终评分(X)',
            dataIndex: 'min',
            render: (text, record) => (
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Form.Item
                        style={{ margin: 0 }}
                        validateStatus={isError(record.type, 'min') || isError1(record.type) || isError2(record.type)}
                        help=""
                    >
                        {getFieldDecorator(`evaluationMin${record.type}`, {
                            initialValue: text,
                            rules: [
                                {
                                    validator(rule, value, callback) {
                                        if (
                                            fullError ||
                                            isError(record.type, 'min') ||
                                            isError1(record.type) ||
                                            isError2(record.type)
                                        ) {
                                            callback(' ');
                                        }
                                        callback();
                                    }
                                }
                            ]
                        })(
                            <Select
                                dropdownClassName={styles.customSelect}
                                style={{ width: 140 }}
                                dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                getPopupContainer={trigger => trigger.parentElement}
                                placeholder="请选择"
                                allowClear
                                onChange={() => setFullError('')}
                            >
                                {levelList.map(item => (
                                    <Option value={item.value} key={item.value}>
                                        {item.label}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                    <span style={{ margin: '0 8px' }}>
                        {form.getFieldValue(`evaluationMin${record.type}`) === 0 ? '≤' : '<'}
                        {' X ≤'}
                    </span>
                    <Form.Item
                        style={{ margin: 0 }}
                        validateStatus={
                            isError(record.type, 'max') || isError1(record.type) || isError2(record.type - 1)
                        }
                        help=""
                    >
                        {getFieldDecorator(`evaluationMax${record.type}`, {
                            initialValue: record?.max,
                            rules: [
                                {
                                    validator(rule, value, callback) {
                                        if (
                                            fullError ||
                                            isError(record.type, 'max') ||
                                            isError1(record.type) ||
                                            isError2(record.type - 1)
                                        ) {
                                            callback(' ');
                                        }
                                        callback();
                                    }
                                }
                            ]
                        })(
                            <Select
                                dropdownClassName={styles.customSelect}
                                style={{ width: 140 }}
                                dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                getPopupContainer={trigger => trigger.parentElement}
                                placeholder="请选择"
                                allowClear
                                onChange={() => setFullError('')}
                            >
                                {levelList.map(item => (
                                    <Option value={item.value} key={item.value}>
                                        {item.label}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                </div>
            )
        },
        {
            title: <InfoIcon title="选择等级后，当大于等于选择等级时则为合格">合格标准</InfoIcon>,
            dataIndex: 'qualified',
            render: (text, record) => (
                <Form.Item style={{ margin: 0 }}>
                    {getFieldDecorator(`qualified${record.type}`, {
                        initialValue: text,
                        rules: [
                            {
                                validator(rule, value, callback) {
                                    const min = form.getFieldValue(`evaluationMin${record.type}`);
                                    const max = form.getFieldValue(`evaluationMax${record.type}`);
                                    if (value && typeof min === 'undefined' && typeof max === 'undefined') {
                                        callback('不可选择空的评分等级');
                                    }
                                    const values = form.getFieldsValue();
                                    let nowQualified;
                                    let nowEntry;
                                    [1, 2, 3, 4, 5].forEach(item => {
                                        if (values?.[`qualified${item}`] > 0) {
                                            nowQualified = item;
                                        }
                                        if (values?.[`entry${item}`] > 0) {
                                            nowEntry = item;
                                        }
                                    });
                                    if (
                                        value &&
                                        typeof nowQualified !== 'undefined' &&
                                        typeof nowEntry !== 'undefined' &&
                                        nowQualified < nowEntry
                                    ) {
                                        callback('不可高于提前转正标准');
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <Radio.Group onChange={e => handleQualifiedChange(e, record.type)}>
                            <Radio value={1}></Radio>
                        </Radio.Group>
                    )}
                </Form.Item>
            )
        },
        {
            title: <InfoIcon title="选择等级后，当大于等于选择等级时则可以提前转正">提前转正标准</InfoIcon>,
            dataIndex: 'entry',
            render: (text, record) => (
                <Form.Item style={{ margin: 0 }}>
                    {getFieldDecorator(`entry${record.type}`, {
                        initialValue: text,
                        rules: [
                            {
                                validator(rule, value, callback) {
                                    const min = form.getFieldValue(`evaluationMin${record.type}`);
                                    const max = form.getFieldValue(`evaluationMax${record.type}`);
                                    if (value && typeof min === 'undefined' && typeof max === 'undefined') {
                                        callback('不可选择空的评分等级');
                                    }

                                    const values = form.getFieldsValue();
                                    let nowQualified;
                                    let nowEntry;
                                    [1, 2, 3, 4, 5].forEach(item => {
                                        if (values?.[`qualified${item}`] > 0) {
                                            nowQualified = item;
                                        }
                                        if (values?.[`entry${item}`] > 0) {
                                            nowEntry = item;
                                        }
                                    });
                                    if (
                                        value &&
                                        typeof nowQualified !== 'undefined' &&
                                        typeof nowEntry !== 'undefined' &&
                                        nowQualified < nowEntry
                                    ) {
                                        callback('不可低于合格标准');
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <Radio.Group onChange={e => handleEntryChange(e, record.type)}>
                            <Radio value={1}></Radio>
                        </Radio.Group>
                    )}
                </Form.Item>
            )
        }
    ];

    const getFinalList = () =>
        [1, 2, 3, 4, 5].map(item => {
            const level = EVALUATION_LEVEL[item];
            const obj = levels.find(it => it.level === level || it.type === item) || {
                min: undefined,
                max: undefined,
                qualified: 0,
                entry: 0
            };
            return { ...obj, type: item, level };
        });

    return (
        <>
            <ProjectPreview
                visible={visible}
                onVisibleChange={setVisible}
                projectName={assessTable?.projectName}
                project={assessTable?.project}
                projectExplain={assessTable?.projectExplain}
            />

            <Form>
                <Form.Item label="评估说明" style={{ marginBottom: 12, maxWidth: 800 }}>
                    {getFieldDecorator('projectExplain', {
                        initialValue: data?.projectExplain || '',
                        rules: [
                            {
                                required: true,
                                message: '请输入评估说明'
                            }
                        ]
                    })(
                        <LimitInput
                            area
                            placeholder="请输入评估说明"
                            autoSize={{ minRows: 3, maxRows: 6 }}
                            maxLength={4000}
                        />
                    )}
                </Form.Item>
                <Form.Item label="评估等级划分" required>
                    <Table
                        rowKey="type"
                        columns={columns}
                        dataSource={getFinalList() || []}
                        pagination={false}
                        scroll={{ x: 'max-content' }}
                    />
                    {fullError && <div style={{ color: '#f5222d', lineHeight: 1, marginTop: 8 }}>{fullError}</div>}
                    {(isError1(1) || isError1(2) || isError1(3) || isError1(4) || isError1(5)) && (
                        <div style={{ color: '#f5222d', lineHeight: 1, marginTop: 8 }}>
                            最终评分请保证右边数值大于左边；
                        </div>
                    )}
                    {(isError2(1) || isError2(2) || isError2(3) || isError2(4)) && (
                        <div style={{ color: '#f5222d', lineHeight: 1, marginTop: 8 }}>
                            最终评分请保证上面等级数值大于下面等级；
                        </div>
                    )}
                </Form.Item>
            </Form>
        </>
    );
});
